package com.caojin.propertyInjector.locationResolver;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

import com.caojin.propertyInjector.UrlResolver;
import com.caojin.util.FileUtil;

/**
 * 文件位置解析器
 * 
 * @author caojin
 */
public class FileSyslocationResolver extends LocationResolver {

	//默认文件夹
	public final static String DEFAULT_FILE_FOLDER = FileSyslocationResolver.class
			.getResource(UrlResolver.PATH_SPLITOR).getPath();
	// 文件夹
	private String folder;
	// 文件名
	private String fileName;
	// 是否递归
	private boolean recursive;

	public FileSyslocationResolver() {
		this(DEFAULT_FILE_NAME);
	}

	public FileSyslocationResolver(String fileName) {
		this(DEFAULT_FILE_FOLDER, fileName);
	}

	public FileSyslocationResolver(String folder, String fileName) {
		this(folder, fileName, Boolean.FALSE);
	}

	public FileSyslocationResolver(String folder, String fileName,
			boolean recursive) {
		super(fileName);
		this.folder = folder;
		this.fileName = fileName;
		this.recursive = recursive;
	}

	@Override
	public InputStream getInputStream() {
		String filePath = getBaseUrl();
		InputStream in = null;
		try {
			in = new FileInputStream(filePath);
		} catch (FileNotFoundException e) {
			throw new UnlocatedException("File Not Found: " + filePath);
		}
		return in;
	}

	@Override
	protected String getBaseUrl() {
		try {
			folder = URLDecoder.decode(folder, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			throw new RuntimeException(e);
		}
		if (!recursive) {
			return folder.concat(File.separator).concat(fileName);
		} else {
			String filePath = FileUtil.getAbsolutePath(folder, fileName);
			if (filePath != FileUtil.FILE_NOT_FOUND) {
				return filePath;
			}
			throw new UnlocatedException("File Not Found: [folder=" + folder
					+ ",fileName=" + fileName + "]");
		}
	}
}